<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
use Illuminate\Http\Response;

$app->get('/my_surprice', function(){
  $info =  main("my_surprice");
  $userId = $info["userid"];
  //$userId = 1;
  $result = DB::select("SELECT surprice.subject,consumer_surprice.verify_code,consumer_surprice.created_at
    FROM consumer_surprice INNER JOIN surprice ON surprice.id = consumer_surprice.surprice_id 
    WHERE consumer_surprice.consumer_id = $userId AND consumer_surprice.surprice_id != 0 
    ORDER BY consumer_surprice.created_at DESC");
  return view("surprices",['result'=> $result]);
});
$app->get('/surpricee', function(){
  $info =  main("surpricee");
  $userId = $info["userid"];
  //$userId = 1;
  $count = DB::table("consumer_surprice")->where("consumer_id",$userId)->where("created_at","LIKE",date("Y-m-d")."%")->count();
 if($count > 9)
   return view("get_surprice",['error' => true, 'msg'=>'今天运气已用完，明天再来试吧！']);

  $time = date("Y-m-d H:i:s");
  $result = DB::select("SELECT id,probability FROM surprice 
    WHERE is_delete= 0 AND is_visible= 0 AND count>count_get AND now() > start_time AND now() < end_time");
  $surpriceId = 0;
  if(!empty($result)){
    $number      = rand(1,100*count($result));
    $key         = floor($number/100);
    $probability = $number%100;
    if($probability <= $result[$key]->probability){
      $surpriceId = $result[$key]->id;
    }
  }
  $verifyCode = ($surpriceId == 0)?"":getCode();
  DB::table("consumer_surprice")->insert(["consumer_id"=>$userId,"surprice_id"=>$surpriceId,"verify_code"=>$verifyCode]);

  if($surpriceId == 0)
    return view("get_surprice",['error' => false, 'msg'=>'没有扫到奖品，再接再厉吧！']);

  $surpriceResult = DB::select("SELECT subject,img_dir,content,count_get FROM surprice WHERE id = $surpriceId");
  DB::table("surprice")->where("id",$surpriceId)->update(["count_get"=>$surpriceResult[0]->count_get + 1]);
  $surpriceResult[0]->verify_code = $verifyCode;
  return view("get_surprice",['error' => false,'data'=> $surpriceResult[0], 'msg'=>'恭喜您！']);
});



$app->get('/my_coupons', function(){
  $info = main("my_coupons");
  return view("cards",['userid' => $info["userid"], 'signPackage'=>$info["signPackage"]]);
});

$app->get('/coupon/{id}/get', function($id){ 
  $info = main("coupon/$id/get");
  return view("get_coupon",['userid' => $info["userid"],'id' => $id, 'signPackage'=>$info["signPackage"]]);
});


function getCode(){
  $arr = ["","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
  return $arr[rand(1,26)].$arr[rand(1,26)].$arr[rand(1,26)].$arr[rand(1,26)].$arr[rand(1,26)].$arr[rand(1,26)];
}

function main($pageName)
{
	//获取openid 
	$appid = "wxd6634286ff92ed40";  
  $secret = "465915b7858df854486ff8d446164796";

  // $get_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
  // $res = httpRequest($get_token_url); 
  // $json_obj = json_decode($res,true);  
  // $access_token = $json_obj['access_token']; 
  // $get_material_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$id";

  // echo "<video src='$get_material_url' controls='controls'></video>";exit;

	$jssdk = new JSSDK($appid, $secret);
	$signPackage = $jssdk->GetSignPackage();	

  // if($id == 0) return view('cards',['userid' => 1,'signPackage'=>$signPackage]);
  // return view('get_coupon',['userid' => 1,'id' => $id,'signPackage'=>$signPackage]);

	if(Session::get('userid')){
		//查找
		$userid = Session::get('userid');
		return ['userid' => $userid, 'signPackage'=>$signPackage];
	}

	// if(isset($_GET['code'])){
 //    	$code = $_GET['code'];
 //    	$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';

	//     $res = httpRequest($get_token_url); 

	//     $json_obj = json_decode($res,true);  
	      
	//     //根据openid和access_token查询用户信息  
	//     $access_token = $json_obj['access_token'];  
	//     $openid = $json_obj['openid'];  
	//     $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';  

	//     $res = httpRequest($get_user_info_url);     
	//     //解析json  
	//     $user_obj = json_decode($res,true);
 //        $consumerData = DB::table('consumer')->select('*')->where('openid',$user_obj['openid'])->get();
 //        if(!$consumerData){
	//         $userid = DB::table('consumer')->insertGetId(array( 'openid' => $user_obj['openid'],
	// 		        											'nickname' => $user_obj['nickname'],
	// 		        											'sex' => $user_obj['sex'],
	// 		        											'city' => $user_obj['city'],
	// 		        											'province' => $user_obj['province'],
	// 		        											'country' => $user_obj['country'],
	// 		        											'headimgurl'=>$user_obj['headimgurl']
	// 	        										));
 //        }else{
 //        	$userid = $consumerData[0]->id;
 //        }
 //        Session::put('userid',$userid);
 //        Session::save();
	// 	return ['userid' => $userid, 'signPackage'=>$signPackage];
	// }
	//   //请求授权
 //    $REDIRECT_URI=urlencode("http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]);
 //    $state = 'init';

 //    $scope='snsapi_userinfo ';
 //    $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$REDIRECT_URI.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
 //    Header("Location: $url");exit;
    if(!empty($_GET['sign']) && !empty($_GET['openid']) && !empty($_GET['nickname'])){
        if($_GET['sign'] != md5($_GET['openid'].$_GET['nickname']."coupon"))
          return false;

        $consumerData = DB::table('consumer')->select('*')->where('openid',$_GET['openid'])->get();
        if(!$consumerData){
            $userid = DB::table('consumer')->insertGetId(array( 'openid' => $_GET['openid'],
                                   'nickname' => $_GET['nickname'],
                                   'sex' => $_GET['sex'],
                                   'city' => $_GET['city'],
                                   'province' => $_GET['province'],
                                   'country' => $_GET['country'],
                                   'headimgurl'=> urldecode($_GET['headimgurl'])
                               ));
        }else{
           $userid = $consumerData[0]->id;
        }
        Session::put('userid',$userid);
        Session::save();

        return ['userid' => $userid, 'signPackage'=>$signPackage];
    }else{
        Header("Location: http://www.chinalove99.net/weixin4/redirect2.php?page=".urlencode($pageName));exit;
    }
}

function httpRequest($url, $data=null){

		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);  //1：回复内容 0：输出内容
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false); 
		if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1); //模拟post方式
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//执行事务
		$output = curl_exec($curl);
		//关闭
		curl_close($curl);
		//输出内容
		return $output;	
}


$app->get('/', function()
{
	if(!Session::get('name')){
		return view('login');
	}
	return view('index');
});
//seller
$app->get('/city/{code}/seller',                'SellerController@index');
//coupon
$app->get('/city/{code}/coupon',                'CouponController@index');
//consumer_coupon
$app->get 	('/{table:[A-Z_a-z]+}/config', 			    'ApiController@config'		);

$app->get 	('/{table:[A-Z_a-z]+}', 					'ApiController@index'		);
$app->get 	('/{table:[A-Z_a-z]+}/{id:[0-9]+}', 		'ApiController@show'		);

//upload file
$app->post 	('/file', 					                'ApiController@upload'		);

$app->post 	('/{table:[A-Z_a-z]+}', 					'ApiController@store'		);
$app->put 	('/{table:[A-Z_a-z]+}/{id:[0-9]+}', 		'ApiController@update'		);
$app->delete('/{table:[A-Z_a-z]+}/{id:[0-9]+}', 		'ApiController@destroy'	);

$app->get 	('/config/init', 						'ConfigController@init'		);

$app->get('/consumer/{id}/coupon',                'ConsumerCouponController@index');
$app->get('/consumer/{id}/coupon/{coupon_id}',      'ConsumerCouponController@show');
$app->get('/user/{id}/coupon/{coupon_id}/use',      'ConsumerCouponController@userConpon');
$app->post('/consumer/{id}/coupon/{coupon_id}/use',      'ConsumerCouponController@useConpon');
$app->post('/consumer/{id}/coupon',              	'ConsumerCouponController@store');
$app->delete('/consumer/{id}/coupon/{coupon_id}',     'ConsumerCouponController@destroy');

$app->get('/consumer/{id}/seller',                  'ConsumerSellerController@index');


//User
$app->get('/user/session',               'UserController@check');
$app->post('/user/login',                'UserController@login');
$app->get('/user/logout',                'UserController@logout');
$app->post('/user/password/{id}',        'UserController@password');


class JSSDK {
  private $appId;
  private $appSecret;

  public function __construct($appId, $appSecret) {
    $this->appId = $appId;
    $this->appSecret = $appSecret;
  }

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();

    // 注意 URL 一定要动态获取，不能 hardcode.
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    $timestamp = time();
    $nonceStr = $this->createNonceStr();

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "signature" => $signature,
      "rawString" => $string
    );
    return $signPackage; 
  }

  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  private function getJsApiTicket() {
    // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("weixinjs/jsapi_ticket.json"));
    if ($data->expire_time < time()) {
      $accessToken = $this->getAccessToken();
      // 如果是企业号用以下 URL 获取 ticket
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
      $res = json_decode($this->httpGet($url));
      $ticket = $res->ticket;
      if ($ticket) {
        $data->expire_time = time() + 7000;
        $data->jsapi_ticket = $ticket;
        $fp = fopen("weixinjs/jsapi_ticket.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }

    return $ticket;
  }

  private function getAccessToken() {
    // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
    $data = json_decode(file_get_contents("weixinjs/access_token.json"));
    if ($data->expire_time < time()) {
      // 如果是企业号用以下URL获取access_token
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        $fp = fopen("weixinjs/access_token.json", "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }

  private function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }
}
?>